package com.test.deencredit.fragment_deencredit.main_deencredit;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager2.widget.ViewPager2;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;

import com.test.deencredit.analytics_deencredit.util_deencredit.AnalyticsUtil_deencredit;
import com.test.deencredit.R;
import com.test.deencredit.activity_deencredit.ln_deencredit.LnAplyActivity_deencredit;
import com.test.deencredit.activity_deencredit.ln_deencredit.MainActivity_deencredit;
import com.test.deencredit.activity_deencredit.process_deencredit.ProcessActivity_deencredit;
import com.test.deencredit.adapter_deencredit.HomeCarouselAdapter_deencredit;
import com.test.deencredit.base_deencredit.BaseLnFragment_deencredit;
import com.test.deencredit.bean_deencredit.config_deencredit.AppShowCustomize_deencredit;
import com.test.deencredit.bean_deencredit.process_deencredit.ProcessInfo_deencredit;
import com.test.deencredit.bean_deencredit.userinfo_deencredit.LnLimitInfo_deencredit;
import com.test.deencredit.config_deencredit.PermissionConfig_deencredit;
import com.test.deencredit.config_deencredit.UserState_deencredit;
import com.test.deencredit.dialog_deencredit.CustomerServiceDialog_deencredit;
import com.test.deencredit.dialog_deencredit.ProcessBottomDialog_deencredit;
import com.test.deencredit.util_deencredit.UserInfoUtil_deencredit;
import com.test.deencredit.util_deencredit.http_deencredit.HttpUtil_deencredit;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class HomeFragment_deencredit extends BaseLnFragment_deencredit implements EasyPermissions.PermissionCallbacks,EasyPermissions.RationaleCallbacks{

    private final ArrayList<HomeCarouselAdapter_deencredit.HomeCarouseInfo_deencredit> homeCarouseInfos_deencredit = new ArrayList<>();

    private ImageButton customerserviceIb_deencredit;
    private ViewPager2 carouseViewpage2_deencredit;
    private Button applyBtn_deencredit;
    private View processView_deencredit, dsView_deencredit, contactusView_deencredit;

    private Runnable processRunnable_deencredit;

    private final Runnable applyRunnable_deencredit = () -> {

        HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"APPLY_CLICK","");

        String[] homePermissions = AppShowCustomize_deencredit.getInstance_deencredit().getHomePermission_deencredit();

        if (PermissionConfig_deencredit.checkPermissions_deencredit(requireActivity(), homePermissions)) {
            //device info upload
            try {
                if (UserInfoUtil_deencredit.getInstance_deencredit().didLogin_deencredit()) {
                    AnalyticsUtil_deencredit.INSTANCE.saveDeviceS2SInfo_deencredit();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //申请流程
            processRunnable_deencredit = () -> {
                //无流程：跳转到申请页
                if (ProcessInfo_deencredit.getInstance_deencredit().getSteps_deencredit().isEmpty())
                    startActivity(new Intent(requireActivity(), LnAplyActivity_deencredit.class));
                //有流程：跳转到流程页
                else startActivity(new Intent(requireContext(), ProcessActivity_deencredit.class));
            };

            HttpUtil_deencredit.getInstance_deencredit().userProcess_deencredit(requireActivity(),this::onUserProcessResponse_deencredit);

        } else
            EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_all_deencredit), PermissionConfig_deencredit.PermissionCode_Home_deencredit, homePermissions);

    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        page_deencredit = "HOME";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_deencredit, container, false);

        customerserviceIb_deencredit = view.findViewById(R.id.fh_ib_customerservice);
        carouseViewpage2_deencredit = view.findViewById(R.id.fh_viewpage2);
        applyBtn_deencredit = view.findViewById(R.id.fh_btn_apply);
        processView_deencredit = view.findViewById(R.id.fh_view_process);
        dsView_deencredit = view.findViewById(R.id.fh_view_ds);
        contactusView_deencredit = view.findViewById(R.id.fh_view_contactus);

        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.fh_refreshlayout);
        refreshLayout.setOnRefreshListener(() -> {
            HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"REFRESH_CLICK","");
            refreshLayout.setRefreshing(false);
            HttpUtil_deencredit.getInstance_deencredit().userProcess_deencredit(requireActivity(),this::onUserProcessResponse_deencredit);
        });

        initView_deencredit();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        HttpUtil_deencredit.getInstance_deencredit().requestLnLimit_deencredit(requireActivity(),this::onLnLimitResponse_deencredit);
    }

    private void initCarouse_deencredit(){

        homeCarouseInfos_deencredit.clear();

        homeCarouseInfos_deencredit.add(new HomeCarouselAdapter_deencredit.HomeCarouseInfo_deencredit(LnLimitInfo_deencredit.getInstance_deencredit().getLimitAmount_deencredit(), false));
        homeCarouseInfos_deencredit.addAll(LnLimitInfo_deencredit.getInstance_deencredit().getHomeCarouseInfos_deencredit());

        HomeCarouselAdapter_deencredit homeCarouselAdapterdeencredit = new HomeCarouselAdapter_deencredit(requireContext(), homeCarouseInfos_deencredit);
        carouseViewpage2_deencredit.setAdapter(homeCarouselAdapterdeencredit);

        new Thread(() -> {
            int count=0;
            while (++count<Integer.MAX_VALUE){
                try {
                    Thread.sleep(1992);
                    int nextIndex = carouseViewpage2_deencredit.getCurrentItem()+1;
                    if (nextIndex<Integer.MAX_VALUE-2)
                        requireActivity().runOnUiThread(() -> carouseViewpage2_deencredit.setCurrentItem(nextIndex));
                    Thread.sleep(2814);
                } catch (InterruptedException|IllegalStateException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }).start();

    }

    private void initView_deencredit(){

        customerserviceIb_deencredit.setOnClickListener(v -> new CustomerServiceDialog_deencredit(requireContext()).show());
        contactusView_deencredit.setOnClickListener(v -> new CustomerServiceDialog_deencredit(requireContext()).show());

        //申请
        applyBtn_deencredit.setOnClickListener(v -> applyRunnable_deencredit.run());

        processView_deencredit.setOnClickListener(v -> {
            processRunnable_deencredit = () -> new ProcessBottomDialog_deencredit(requireContext(), applyRunnable_deencredit).show();
            HttpUtil_deencredit.getInstance_deencredit().userProcess_deencredit(requireActivity(),this::onUserProcessResponse_deencredit);
        });

        dsView_deencredit.setOnClickListener(v -> {
            String agreementUrl = AppShowCustomize_deencredit.getInstance_deencredit().getAgreementUrl_deencredit();
            if (TextUtils.isEmpty(agreementUrl)) return;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(agreementUrl)));
        });

    }

    public void onUserProcessResponse_deencredit(){
        String state = ProcessInfo_deencredit.getInstance_deencredit().getUserState_deencredit();
        if (UserState_deencredit.isStateChange_deencredit(state)) {//刷新用户状态
            FragmentActivity activity = requireActivity();
            UserState_deencredit.clearState_deencredit();
            activity.startActivity(new Intent(activity, MainActivity_deencredit.class));
            activity.finish();
        }else if (processRunnable_deencredit !=null) {
            processRunnable_deencredit.run();
            processRunnable_deencredit = null;
        }else HttpUtil_deencredit.getInstance_deencredit().requestLnLimit_deencredit(requireActivity(),this::onLnLimitResponse_deencredit);
    }

    public void onLnLimitResponse_deencredit(){
        initCarouse_deencredit();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        applyRunnable_deencredit.run();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this,perms))
            new AppSettingsDialog.Builder(this).build().show();
    }

    @Override
    public void onRationaleAccepted(int requestCode) {}

    @Override
    public void onRationaleDenied(int requestCode) {}

}